<template>
  <div class="page-container">
    <h1>新建租赁单</h1>

    <!-- 步骤指示器 -->
    <div class="steps-container">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="客户信息" description="录入客户基本信息" />
        <el-step title="车辆选择" description="选择租赁车辆" />
        <el-step title="租期设置" description="设置租赁时间和费用" />
        <el-step title="确认提交" description="确认信息并提交" />
      </el-steps>
    </div>

    <div class="content-card">
      <!-- 步骤1: 客户选择 -->
      <div v-if="currentStep === 0" class="step-content">
        <h2>选择客户</h2>

        <!-- 客户搜索区域 -->
        <div class="customer-search-section">
          <el-form :model="customerSearchForm" :inline="true" class="search-form">
            <el-form-item label="客户姓名">
              <el-input
                v-model="customerSearchForm.name"
                placeholder="请输入客户姓名"
                clearable
                @keyup.enter="handleCustomerSearch"
              />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input
                v-model="customerSearchForm.phone"
                placeholder="请输入手机号码"
                clearable
                @keyup.enter="handleCustomerSearch"
              />
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input
                v-model="customerSearchForm.cartNumber"
                placeholder="请输入身份证号"
                clearable
                @keyup.enter="handleCustomerSearch"
              />
            </el-form-item>
            <el-form-item label="客户状态">
              <el-select v-model="customerSearchForm.status" placeholder="请选择状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="正常" value="1" />
                <el-option label="黑名单" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleCustomerSearch" :loading="customerSearching">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleCustomerSearchReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 客户列表 -->
        <div class="customer-list-section">
          <h3>客户列表</h3>
          <el-table
            :data="customerList"
            style="width: 100%"
            v-loading="customerListLoading"
            empty-text="暂无客户数据"
            @row-click="handleCustomerRowClick"
            class="customer-table"
            highlight-current-row
            :current-row="selectedCustomer"
            :row-class-name="getCustomerRowClassName"
          >
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="name" label="姓名" min-width="100" show-overflow-tooltip />
            <el-table-column prop="phone" label="手机号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="cartNumber" label="身份证号" min-width="160" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? '正常' : '黑名单' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="rentalCount" label="租车次数" width="90" align="center">
              <template #default="scope">
                <span class="rental-count">{{ scope.row.rentalTimes || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button
                  size="small"
                  :type="scope.row.status === 2 ? 'danger' : 'primary'"
                  @click.stop="handleSelectCustomer(scope.row)"
                  :disabled="customerForm.customerId === scope.row.id || scope.row.status === 2"
                >
                  {{
                    customerForm.customerId === scope.row.id ? '已选择' :
                    (scope.row.status === 2 ? '黑名单' : '选择')
                  }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="customer-pagination">
            <el-pagination
              v-model:current-page="customerCurrentPage"
              v-model:page-size="customerPageSize"
              :page-sizes="[5, 10, 20, 50]"
              :total="customerTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleCustomerPageSizeChange"
              @current-change="handleCustomerPageChange"
            />
          </div>
        </div>

        <!-- 选中客户的详细信息 -->
        <div v-if="selectedCustomer" class="selected-customer-details">
          <h3>已选择客户</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="客户ID">{{ selectedCustomer.id }}</el-descriptions-item>
            <el-descriptions-item label="客户姓名">{{ selectedCustomer.name }}</el-descriptions-item>
            <el-descriptions-item label="手机号码">{{ selectedCustomer.phone }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ selectedCustomer.cartNumber }}</el-descriptions-item>
            <el-descriptions-item label="客户状态">
              <el-tag :type="selectedCustomer.status === 1 ? 'success' : 'danger'">
                {{ selectedCustomer.status === 1 ? '正常' : '黑名单' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="租车次数">{{ selectedCustomer.rentalTimes || 0 }} 次</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 步骤2: 车辆选择 -->
      <div v-if="currentStep === 1" class="step-content">
        <h2>车辆选择</h2>
        <div class="car-selection">

          <!-- 可用车辆列表 -->
          <div class="car-list-section">
            <h3>可用车辆列表</h3>
            <el-table
              :data="availableCars"
              style="width: 100%"
              v-loading="carListLoading"
              empty-text="暂无可用车辆"
              @row-click="handleCarRowClick"
              class="car-table"
              highlight-current-row
              :current-row="selectedCar"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            >
              <el-table-column prop="plateNumber" label="车牌号" min-width="120" show-overflow-tooltip />
              <el-table-column prop="brand" label="品牌" min-width="100" show-overflow-tooltip />
              <el-table-column prop="model" label="型号" min-width="120" show-overflow-tooltip />
              <el-table-column prop="status" label="状态" min-width="80" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'" size="small">
                    {{ scope.row.status === '1' ? '可用' : '不可用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="mileage" label="里程(km)" min-width="100" align="center">
                <template #default="scope">
                  {{ scope.row.mileage ? scope.row.mileage.toLocaleString() : '未知' }}
                </template>
              </el-table-column>
              <el-table-column prop="lastMaintenance" label="上次保养" min-width="120" align="center" />
              <el-table-column prop="dailyRate" label="日租金" min-width="100" align="center">
                <template #default="scope">
                  <span class="price-text">¥{{ scope.row.dailyRate }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click.stop="handleSelectCar(scope.row)"
                    :disabled="carForm.carId === scope.row.id || scope.row.status !== '1'"
                  >
                    {{ carForm.carId === scope.row.id ? '已选择' : (scope.row.status === '1' ? '选择' : '不可用') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="car-pagination">
              <el-pagination
                v-model:current-page="carCurrentPage"
                v-model:page-size="carPageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="carTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleCarPageSizeChange"
                @current-change="handleCarPageChange"
              />
            </div>
          </div>

          <!-- 选中车辆的详细信息 -->
          <div v-if="selectedCar" class="car-details">
            <h3>已选择车辆</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="车牌号">{{ selectedCar.plateNumber }}</el-descriptions-item>
              <el-descriptions-item label="品牌型号">{{ selectedCar.brand }} {{ selectedCar.model }}</el-descriptions-item>
              <el-descriptions-item label="车辆状态">
                <el-tag :type="selectedCar.status === '1' ? 'success' : 'danger'">
                  {{ selectedCar.status === '1' ? '可用' : '不可用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="日租金">¥{{ selectedCar.dailyRate }}</el-descriptions-item>
              <el-descriptions-item label="里程数">{{ selectedCar.mileage ? selectedCar.mileage.toLocaleString() + ' km' : '未知' }}</el-descriptions-item>
              <el-descriptions-item label="上次保养">{{ selectedCar.lastMaintenance || '未知' }}</el-descriptions-item>
              <el-descriptions-item label="下次保养" :span="2">{{ selectedCar.nextMaintenance || '未知' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </div>

      <!-- 步骤3: 租期设置 -->
      <div v-if="currentStep === 2" class="step-content">
        <h2>租期设置</h2>
        <el-form
          ref="rentalFormRef"
          :model="rentalForm"
          :rules="rentalRules"
          label-width="120px"
          class="rental-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="startDate">
                <el-date-picker
                  v-model="rentalForm.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  :disabled-date="disabledStartDate"
                  @change="calculateTotalAmount"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                  v-model="rentalForm.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  :disabled-date="disabledEndDate"
                  @change="calculateTotalAmount"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="租赁天数">
                <el-input :value="rentalDays + ' 天'" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日租金">
                <el-input :value="'¥' + (selectedCar?.dailyRate || 0)" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="押金金额" prop="deposit">
            <el-input-number
              v-model="rentalForm.deposit"
              :min="0"
              :precision="2"
              placeholder="请输入押金金额"
            />
          </el-form-item>

          <el-form-item label="总金额">
            <el-input :value="'¥' + totalAmount" disabled class="total-amount" />
          </el-form-item>

          <el-form-item label="备注信息">
            <el-input
              v-model="rentalForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入租赁备注信息（可选）"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤4: 确认提交 -->
      <div v-if="currentStep === 3" class="step-content">
        <h2>确认租赁信息</h2>
        <div class="confirmation-content">
          <el-descriptions title="客户信息" :column="2" border>
            <el-descriptions-item label="客户ID">{{ customerForm.customerId }}</el-descriptions-item>
            <el-descriptions-item label="客户姓名">{{ customerForm.name }}</el-descriptions-item>
            <el-descriptions-item label="手机号码">{{ customerForm.phone }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ customerForm.cartNumber }}</el-descriptions-item>
            <el-descriptions-item label="客户状态" :span="2">
              <el-tag :type="selectedCustomer?.status === 1 ? 'success' : 'danger'">
                {{ selectedCustomer?.status === 1 ? '正常' : '黑名单' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions title="车辆信息" :column="2" border style="margin-top: 20px;">
            <el-descriptions-item label="车牌号">{{ selectedCar?.plateNumber }}</el-descriptions-item>
            <el-descriptions-item label="品牌型号">{{ selectedCar?.brand }} {{ selectedCar?.model }}</el-descriptions-item>
            <el-descriptions-item label="车辆状态">
              <el-tag :type="selectedCar?.status === '1' ? 'success' : 'danger'">
                {{ selectedCar?.status === '1' ? '可用' : '不可用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="日租金">¥{{ selectedCar?.dailyRate }}</el-descriptions-item>
            <el-descriptions-item label="里程数">{{ selectedCar?.mileage ? selectedCar.mileage.toLocaleString() + ' km' : '未知' }}</el-descriptions-item>
            <el-descriptions-item label="上次保养">{{ selectedCar?.lastMaintenance || '未知' }}</el-descriptions-item>
          </el-descriptions>

          <el-descriptions title="租赁信息" :column="2" border style="margin-top: 20px;">
            <el-descriptions-item label="开始日期">{{ formatDate(rentalForm.startDate) }}</el-descriptions-item>
            <el-descriptions-item label="结束日期">{{ formatDate(rentalForm.endDate) }}</el-descriptions-item>
            <el-descriptions-item label="租赁天数">{{ rentalDays }} 天</el-descriptions-item>
            <el-descriptions-item label="押金金额">¥{{ rentalForm.deposit }}</el-descriptions-item>
            <el-descriptions-item label="总金额" :span="2">
              <span class="total-amount-text">¥{{ totalAmount }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="step-actions">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="currentStep < 3" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="currentStep === 3" type="success" @click="submitRental" :loading="submitting">
          提交租赁单
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 当前步骤
const currentStep = ref(0)
const submitting = ref(false)

// 表单引用
const rentalFormRef = ref(null)

// 客户选择相关数据
const customerForm = reactive({
  customerId: null,
  name: '',
  phone: '',
  cartNumber: ''
})

// 客户搜索表单
const customerSearchForm = reactive({
  name: '',
  phone: '',
  cartNumber: '',
  status: ''
})

// 客户列表和分页
const customerList = ref([])
const selectedCustomer = ref(null)
const customerListLoading = ref(false)
const customerSearching = ref(false)
const customerCurrentPage = ref(1)
const customerPageSize = ref(10)
const customerTotal = ref(0)

// 车辆选择表单
const carForm = reactive({
  carId: null
})

// 租赁信息表单
const rentalForm = reactive({
  startDate: '',
  endDate: '',
  deposit: 1000,
  remark: ''
})

// 可用车辆列表和分页
const availableCars = ref([])
const selectedCar = ref(null)
const carListLoading = ref(false)
const carCurrentPage = ref(1)
const carPageSize = ref(10)
const carTotal = ref(0)

// 表单验证规则（客户选择不需要表单验证规则）

const rentalRules = {
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  deposit: [
    { required: true, message: '请输入押金金额', trigger: 'blur' }
  ]
}

// 计算属性
const rentalDays = computed(() => {
  if (rentalForm.startDate && rentalForm.endDate) {
    const start = new Date(rentalForm.startDate)
    const end = new Date(rentalForm.endDate)
    const diffTime = Math.abs(end - start)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays || 1
  }
  return 0
})

const totalAmount = computed(() => {
  if (selectedCar.value && rentalDays.value > 0) {
    return (selectedCar.value.dailyRate * rentalDays.value + rentalForm.deposit).toFixed(2)
  }
  return '0.00'
})

// 客户相关方法
const fetchCustomerList = async (isSearch = false) => {
  try {
    if (isSearch) {
      customerSearching.value = true
    } else {
      customerListLoading.value = true
    }

    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    // 构建查询参数
    const params = new URLSearchParams({
      page: customerCurrentPage.value,
      size: customerPageSize.value
    })

    // 添加搜索条件
    if (customerSearchForm.name) params.append('name', customerSearchForm.name)
    if (customerSearchForm.phone) params.append('phone', customerSearchForm.phone)
    if (customerSearchForm.cartNumber) params.append('cartNumber', customerSearchForm.cartNumber)
    if (customerSearchForm.status) params.append('status', customerSearchForm.status)

    const url = `http://localhost:8080/customers/list?${params.toString()}`
    console.log('获取客户列表，请求URL:', url)

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    console.log('获取客户列表响应:', result)

    if (result.code === 200) {
      // 处理客户列表数据
      customerList.value = result.data.records || []
      customerTotal.value = result.data.total || 0
      customerCurrentPage.value = result.data.current || 1
      customerPageSize.value = result.data.size || 10

      if (isSearch && customerList.value.length === 0) {
        ElMessage.info('未找到符合条件的客户')
      }
    } else {
      ElMessage.error(result.message || '获取客户列表失败')
    }
  } catch (error) {
    console.error('获取客户列表错误:', error)
    ElMessage.error('获取客户列表失败，请检查网络连接')
  } finally {
    customerListLoading.value = false
    customerSearching.value = false
  }
}

// 客户搜索处理
const handleCustomerSearch = () => {
  customerCurrentPage.value = 1
  fetchCustomerList(true)
}

// 重置客户搜索
const handleCustomerSearchReset = () => {
  Object.assign(customerSearchForm, {
    name: '',
    phone: '',
    cartNumber: '',
    status: ''
  })
  customerCurrentPage.value = 1
  fetchCustomerList()
}

// 客户分页处理
const handleCustomerPageChange = (page) => {
  customerCurrentPage.value = page
  fetchCustomerList()
}

const handleCustomerPageSizeChange = (size) => {
  customerPageSize.value = size
  customerCurrentPage.value = 1
  fetchCustomerList()
}

// 客户选择处理
const handleSelectCustomer = (customer) => {
  // 检查客户状态，黑名单客户不能选择
  if (customer.status === 2) {
    ElMessage.warning('该客户为黑名单，无法选择')
    return
  }

  customerForm.customerId = customer.id
  customerForm.name = customer.name
  customerForm.phone = customer.phone
  customerForm.cartNumber = customer.cartNumber
  selectedCustomer.value = customer
}

const handleCustomerRowClick = (row) => {
  // 黑名单客户不能通过点击行选择
  if (row.status === 2) {
    ElMessage.warning('该客户为黑名单，无法选择')
    return
  }
  handleSelectCustomer(row)
}

// 客户行样式类名
const getCustomerRowClassName = ({ row }) => {
  if (row.status === 2) {
    return 'blacklist-row' // 黑名单行样式
  }
  return ''
}

// 车辆相关方法
const fetchAvailableCars = async (statusFilter = '1', page = 1) => {
  try {
    carListLoading.value = true
    const token = localStorage.getItem('Token')

    // 构建查询参数
    const params = new URLSearchParams({
      page: page,
      size: carPageSize.value
    })

    if (statusFilter) {
      params.append('status', statusFilter)
    }

    const url = `http://localhost:8080/car/available?${params.toString()}`
    console.log('获取可用车辆列表，请求URL:', url)

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    console.log('获取车辆列表响应:', result)

    if (result.code === 200) {
      // 处理分页数据
      if (result.data && typeof result.data === 'object' && result.data.records) {
        // 分页格式的数据 - 处理实际的车辆数据结构
        const processedCars = result.data.records.map(car => ({
          id: car.id,
          brand: car.brand,
          model: car.model,
          plateNumber: car.plateNumber,
          type: car.type || 'unknown', // 如果没有type字段，设置默认值
          color: car.color || '未知', // 如果没有color字段，设置默认值
          seats: car.seats || 5, // 如果没有seats字段，设置默认值
          dailyRate: car.dailyRate || car.price || 100, // 日租金字段可能叫price
          status: car.status,
          lastMaintenance: car.lastMaintenance,
          nextMaintenance: car.nextMaintenance,
          mileage: car.mileage
        }))

        availableCars.value = processedCars
        carTotal.value = result.data.total || 0
        carCurrentPage.value = result.data.current || 1
      } else {
        // 简单数组格式的数据
        availableCars.value = result.data || []
        carTotal.value = (result.data || []).length
        carCurrentPage.value = 1
      }
    } else {
      throw new Error(result.message || '获取车辆列表失败')
    }
  } catch (error) {
    console.error('获取车辆列表失败：', error)
    ElMessage.error('获取车辆列表失败：' + error.message)
    availableCars.value = []
    carTotal.value = 0
  } finally {
    carListLoading.value = false
  }
}



// 车辆列表分页处理
const handleCarPageChange = (page) => {
  carCurrentPage.value = page
  fetchAvailableCars('1', page) // 固定显示可用车辆
}

const handleCarPageSizeChange = (size) => {
  carPageSize.value = size
  carCurrentPage.value = 1
  fetchAvailableCars('1', 1) // 固定显示可用车辆
}

// 车辆选择方法
const handleSelectCar = (car) => {
  carForm.carId = car.id
  selectedCar.value = car
  calculateTotalAmount()
}

const handleCarRowClick = (row) => {
  handleSelectCar(row)
}

const calculateTotalAmount = () => {
  // 触发计算属性重新计算
}

// 由于后端数据中没有车辆类型字段，暂时移除此函数

const disabledStartDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const disabledEndDate = (time) => {
  if (rentalForm.startDate) {
    return time.getTime() <= new Date(rentalForm.startDate).getTime()
  }
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期为 yyyy-MM-dd 格式 (LocalDate)
const formatDateToLocalDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 步骤控制
const nextStep = async () => {
  let isValid = false

  switch (currentStep.value) {
    case 0:
      // 检查是否选择了客户
      if (customerForm.customerId) {
        isValid = true
      } else {
        ElMessage.warning('请选择一个客户')
        isValid = false
      }
      break
    case 1:
      // 检查是否选择了车辆
      if (carForm.carId) {
        isValid = true
      } else {
        ElMessage.warning('请选择一辆车辆')
        isValid = false
      }
      break
    case 2:
      if (rentalFormRef.value) {
        await rentalFormRef.value.validate((valid) => {
          isValid = valid
        })
      }
      break
  }

  if (isValid) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 提交租赁单
const submitRental = async () => {
  try {
    submitting.value = true

    const token = localStorage.getItem('Token')
    // 构建车辆信息字符串
    const carInfo = selectedCar.value ?
      `${selectedCar.value.brand} ${selectedCar.value.model} ${selectedCar.value.plateNumber}` : ''

    const requestData = {
      // 客户信息
      customerId: customerForm.customerId,
      customerName: customerForm.name,
      customerPhone: customerForm.phone,
      customerIdCard: customerForm.cartNumber,

      // 车辆信息
      carId: carForm.carId,
      carInfo: carInfo,

      // 租赁信息 - 使用 LocalDate 格式 (yyyy-MM-dd)
      startRentalTime: formatDateToLocalDate(rentalForm.startDate),
      endRentalTime: formatDateToLocalDate(rentalForm.endDate),
      deposit: rentalForm.deposit,
      money: totalAmount.value,
      rentalRemark: rentalForm.remark,
      status: 0 // 待审核状态
    }

    console.log('提交租赁单数据:', requestData)

    const response = await fetch('http://localhost:8080/rental/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      },
      body: JSON.stringify(requestData)
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('租赁单创建成功！')

      // 询问是否继续创建新的租赁单
      ElMessageBox.confirm('租赁单已成功创建，是否继续创建新的租赁单？', '提示', {
        confirmButtonText: '继续创建',
        cancelButtonText: '返回首页',
        type: 'success'
      }).then(() => {
        // 重置表单
        resetAllForms()
        currentStep.value = 0
      }).catch(() => {
        // 返回首页
        router.push('/employee')
      })
    } else {
      throw new Error(result.message || '创建租赁单失败')
    }
  } catch (error) {
    console.error('创建租赁单失败：', error)
    ElMessage.error('创建租赁单失败：' + error.message)
  } finally {
    submitting.value = false
  }
}

// 重置所有表单
const resetAllForms = () => {
  // 重置客户选择
  Object.assign(customerForm, {
    customerId: null,
    name: '',
    phone: '',
    cartNumber: ''
  })
  selectedCustomer.value = null

  // 重置车辆选择
  Object.assign(carForm, {
    carId: null
  })
  selectedCar.value = null

  // 重置租赁信息
  Object.assign(rentalForm, {
    startDate: '',
    endDate: '',
    deposit: 1000,
    remark: ''
  })

  // 重置客户搜索
  Object.assign(customerSearchForm, {
    name: '',
    phone: '',
    cartNumber: '',
    status: ''
  })

  // 重置分页
  customerCurrentPage.value = 1
  carCurrentPage.value = 1
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCustomerList() // 获取客户列表
  fetchAvailableCars('1', 1) // 获取第一页的可用车辆
})
</script>

<style scoped>
.page-container {
  padding: 40px 20px;
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.page-container h1 {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 40px;
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  position: relative;
}

.page-container h1::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.steps-container {
  margin-bottom: 40px;
}

.content-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow:
    0 20px 40px rgba(0, 0, 0, 0.1),
    0 0 0 1px rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
  min-height: 600px;
}

.content-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

.step-content {
  min-height: 450px;
}

.step-content h2 {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 30px;
  text-align: center;
  position: relative;
  padding-bottom: 15px;
}

.step-content h2::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 2px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 1px;
}

.rental-form {
  max-width: 800px;
  margin: 0 auto;
}

.rental-form .el-form-item {
  margin-bottom: 25px;
}

.rental-form .el-form-item__label {
  font-weight: 600;
  color: #2c3e50;
}

.rental-form .el-input__wrapper,
.rental-form .el-select .el-input__wrapper,
.rental-form .el-date-editor .el-input__wrapper {
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.rental-form .el-input__wrapper:hover,
.rental-form .el-select .el-input__wrapper:hover,
.rental-form .el-date-editor .el-input__wrapper:hover {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.rental-form .el-input__wrapper.is-focus,
.rental-form .el-select .el-input__wrapper.is-focus,
.rental-form .el-date-editor .el-input__wrapper.is-focus {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.car-selection {
  max-width: 800px;
  margin: 0 auto;
}

.car-details {
  margin-top: 30px;
  padding: 25px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 15px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.car-details h3 {
  color: #667eea;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

/* 车辆列表样式 */
.car-list-section {
  margin-top: 30px;
}

.car-list-section h3 {
  color: #667eea;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

/* 车辆表格容器 - 支持水平滚动 */
.car-list-section .el-table {
  width: 100%;
  min-width: 800px; /* 设置最小宽度确保所有列都能显示 */
}

.car-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  width: 100%;
}

.car-table .el-table__header-wrapper {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.car-table .el-table__header th {
  background: transparent !important;
  color: white !important;
  font-weight: 600;
  border: none !important;
}

.car-table .el-table__row {
  transition: all 0.2s ease;
  cursor: pointer;
}

.car-table .el-table__row:hover {
  background-color: rgba(102, 126, 234, 0.05) !important;
}

.car-table .el-table__row.current-row {
  background-color: rgba(102, 126, 234, 0.1) !important;
}

.car-table .el-table__cell {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 8px;
}

/* 价格文字样式 */
.price-text {
  font-weight: 600;
  color: #e6a23c;
}

.car-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.car-pagination .el-pagination {
  background: rgba(102, 126, 234, 0.05);
  padding: 15px 20px;
  border-radius: 25px;
}

/* 客户选择样式 */
.customer-search-section {
  margin-bottom: 30px;
  padding: 25px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 15px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.customer-search-section .search-form {
  margin: 0;
}

.customer-search-section .el-form-item {
  margin-bottom: 20px;
  margin-right: 20px;
}

.customer-search-section .el-form-item__label {
  font-weight: 600;
  color: #2c3e50;
}

.customer-search-section .el-input__wrapper,
.customer-search-section .el-select .el-input__wrapper {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.customer-search-section .el-input__wrapper:hover,
.customer-search-section .el-select .el-input__wrapper:hover {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.customer-search-section .el-button {
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.customer-search-section .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.customer-search-section .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.customer-list-section {
  margin-top: 30px;
}

.customer-list-section h3 {
  color: #667eea;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

.customer-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.customer-table .el-table__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.customer-table .el-table__header th {
  background: transparent !important;
  color: white !important;
  font-weight: 600;
  border: none !important;
}

.customer-table .el-table__row {
  transition: all 0.2s ease;
  cursor: pointer;
}

.customer-table .el-table__row:hover {
  background-color: rgba(102, 126, 234, 0.05) !important;
}

.customer-table .el-table__row.current-row {
  background-color: rgba(102, 126, 234, 0.1) !important;
}

.customer-table .el-table__cell {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 8px;
}

/* 黑名单客户行样式 */
.customer-table .el-table__row.blacklist-row {
  background-color: rgba(245, 108, 108, 0.1) !important;
  opacity: 0.7;
  cursor: not-allowed !important;
}

.customer-table .el-table__row.blacklist-row:hover {
  background-color: rgba(245, 108, 108, 0.15) !important;
  transform: none !important;
  box-shadow: none !important;
}

.customer-table .el-table__row.blacklist-row .el-table__cell {
  color: #909399;
}

.customer-table .rental-count {
  display: inline-block;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  min-width: 20px;
  text-align: center;
}

.customer-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.customer-pagination .el-pagination {
  background: rgba(102, 126, 234, 0.05);
  padding: 15px 20px;
  border-radius: 25px;
}

.selected-customer-details {
  margin-top: 30px;
  padding: 25px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 15px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.selected-customer-details h3 {
  color: #667eea;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

.confirmation-content {
  max-width: 900px;
  margin: 0 auto;
}

.confirmation-content .el-descriptions {
  margin-bottom: 25px;
}

.total-amount {
  font-size: 18px;
  font-weight: 600;
  color: #667eea;
}

.total-amount-text {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid rgba(102, 126, 234, 0.1);
}

.step-actions .el-button {
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 25px;
  min-width: 120px;
  transition: all 0.3s ease;
}

.step-actions .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.step-actions .el-button--success {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  border: none;
}

.step-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  /* 车辆表格在中等屏幕上的优化 */
  .car-list-section .el-table {
    min-width: 700px;
  }

  .customer-search-section .el-form-item {
    margin-right: 15px;
  }
}

@media (max-width: 992px) {
  /* 车辆表格在小屏幕上的优化 */
  .car-list-section .el-table {
    min-width: 600px;
    font-size: 13px;
  }

  .car-table .el-table__cell {
    padding: 10px 6px;
  }

  .customer-table {
    font-size: 13px;
  }

  .customer-table .el-table__cell {
    padding: 10px 6px;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 20px 10px;
  }

  .content-card {
    padding: 20px;
    min-height: auto;
  }

  .rental-form,
  .car-selection,
  .confirmation-content {
    max-width: 100%;
  }

  /* 表格容器支持水平滚动 */
  .car-list-section,
  .customer-list-section {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

  .car-list-section .el-table,
  .customer-list-section .el-table {
    min-width: 500px;
    font-size: 12px;
  }

  .car-table .el-table__cell,
  .customer-table .el-table__cell {
    padding: 8px 4px;
  }

  /* 搜索表单在小屏幕上的优化 */
  .customer-search-section .search-form {
    display: block;
  }

  .customer-search-section .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .step-actions {
    flex-direction: column;
    align-items: center;
  }

  .step-actions .el-button {
    width: 100%;
    max-width: 200px;
  }
}

@media (max-width: 576px) {
  /* 超小屏幕优化 */
  .car-list-section .el-table,
  .customer-list-section .el-table {
    min-width: 400px;
    font-size: 11px;
  }

  .car-table .el-button,
  .customer-table .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }

  .customer-search-section {
    padding: 15px;
  }

  .customer-search-section .el-form-item__label {
    font-size: 14px;
  }
}
</style>